/**
 * Handelt die Abort and Goto Messages
 * 
 * @author Matthias Wilhelm
 */
package de.fhin.mas.agents.navigator.behaviours;

import jade.core.Agent;
import jade.domain.FIPANames;
import jade.domain.FIPAAgentManagement.FailureException;
import jade.domain.FIPAAgentManagement.NotUnderstoodException;
import jade.domain.FIPAAgentManagement.RefuseException;
import jade.lang.acl.ACLMessage;
import jade.proto.AchieveREResponder;
import de.fhin.mas.MASEvents;
import de.fhin.mas.MASLocations;
import de.fhin.mas.agents.navigator.NavigatorAgent;
import de.fhin.mas.ontology.Location;
import de.fhin.mas.util.Coordinate;
import de.fhin.mas.util.MessageUtil;

/**
 * 
 * @author Matthias Wilhelm
 * 
 */
public class AbortAndGotoHandler extends AchieveREResponder {

	private static final long serialVersionUID = 7065921347321640935L;

	public AbortAndGotoHandler(Agent a) {
		super(a, MessageUtil.buildBasicCommunicationTemplate(
				FIPANames.InteractionProtocol.FIPA_REQUEST,
				MASEvents.ABORT_AND_GO_TO.getName(), ACLMessage.REQUEST, null));

	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	protected ACLMessage prepareResponse(ACLMessage request)
			throws NotUnderstoodException, RefuseException {

		ACLMessage reply = request.createReply();
		reply.setPerformative(ACLMessage.AGREE);

		return reply;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	protected ACLMessage prepareResultNotification(ACLMessage request,
			ACLMessage response) throws FailureException {
		// TODO: Ziel auslesen und richtig setzen

		ACLMessage reply = request.createReply();
		reply.setPerformative(ACLMessage.INFORM);
		reply.setContent("DONE");

		Location location = ((NavigatorAgent) myAgent)
				.extractLocationFromMsg(request);

		if (location != null) {
			((NavigatorAgent) myAgent).set_myDestination(new Coordinate(
					location.getX_coordinate(), location.getY_coordinate()));
			int type = location.getType();

			if (type == MASLocations.LOCATION_NONE.getType()) {
				((NavigatorAgent) myAgent).target_none();
			} else if (type == MASLocations.LOCATION_OBJECT.getType()) {
				((NavigatorAgent) myAgent).target_object();
			} else if (type == MASLocations.LOCATION_CHARGER.getType()) {
				((NavigatorAgent) myAgent).target_charger();
			} else if (type == MASLocations.LOCATION_STORAGE.getType()) {
				((NavigatorAgent) myAgent)
						.set_storageLocation(new Coordinate(location
								.getX_coordinate(), location.getY_coordinate()));
				((NavigatorAgent) myAgent).target_storage();
			} else if (type == MASLocations.LOCATION_USERDEFINED.getType()) {
				((NavigatorAgent) myAgent).target_none();
			}

		}

		return reply;
	}
}
